<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="材质名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入材质名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
<!--      <el-form-item label="材质类型" prop="materialType">-->
<!--        <el-select-->
<!--          v-model="queryParams.materialType"-->
<!--          placeholder="请选择材质类型"-->
<!--          clearable-->
<!--          class="!w-240px"-->
<!--        >-->
<!--          <el-option label="请选择字典生成" value="" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="材质类型id" prop="materialTypeId">-->
<!--        <el-select-->
<!--          v-model="queryParams.materialTypeId"-->
<!--          placeholder="请选择材质类型id"-->
<!--          clearable-->
<!--          class="!w-240px"-->
<!--        >-->
<!--          <el-option label="请选择字典生成" value="" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <el-form-item label="材质类型" prop="materialType">
        <el-select
          v-model="selectedMaterialType"
          placeholder="请选择材质类型"
          clearable
          class="!w-240px"
          @change="handleMaterialTypeChange"
        >
          <el-option
            v-for="item in materialTypeList"
            :key="item.id"
            :label="item.typeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="材质类型ID" prop="materialTypeId">-->
<!--        <el-input v-model="queryParams.materialTypeId" placeholder="自动填充材质类型ID" readonly />-->
<!--      </el-form-item>-->
      <el-form-item label="楞别" prop="fluteType">
        <el-input
          v-model="queryParams.fluteType"
          placeholder="请输入楞别"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="层数" prop="layer">
        <el-input
          v-model="queryParams.layer"
          placeholder="请输入层数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:base-material:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:base-material:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- 子表的列表 -->
      <el-table-column type="expand">
        <template #default="scope">
          <el-tabs model-value="baseMaterialParameters">
            <el-tab-pane label="参数" name="baseMaterialParameters">
              <BaseMaterialParametersList :material-id="scope.row.id" />
            </el-tab-pane>
            <el-tab-pane label="备注" name="baseMaterialRemarks">
              <BaseMaterialRemarksList :material-id="scope.row.id" />
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-table-column>
<!--      <el-table-column label="材质编号" align="center" prop="id" />-->
      <el-table-column label="材质名称" align="center" prop="materialName" />
      <el-table-column label="材质类型" align="center" prop="materialType" />
<!--      <el-table-column label="材质类型id" align="center" prop="materialTypeId" />-->
      <el-table-column label="楞别" align="center" prop="fluteType" />
      <el-table-column label="层数" align="center" prop="layer" />
      <el-table-column label="密度" align="center" prop="density" />
      <el-table-column label="厚度" align="center" prop="thickness" />
<!--      <el-table-column label="耐破" align="center" prop="burstStrength" />-->
<!--      <el-table-column label="边压" align="center" prop="edgeCompression" />-->
<!--      <el-table-column label="面纸" align="center" prop="facePaper" />-->
<!--      <el-table-column label="瓦楞纸1" align="center" prop="flutePaper1" />-->
<!--      <el-table-column label="芯纸1" align="center" prop="corePaper1" />-->
<!--      <el-table-column label="瓦楞纸2" align="center" prop="flutePaper2" />-->
<!--      <el-table-column label="芯纸2" align="center" prop="corePaper2" />-->
<!--      <el-table-column label="瓦楞纸3" align="center" prop="flutePaper3" />-->
<!--      <el-table-column label="里纸" align="center" prop="innerPaper" />-->
<!--      <el-table-column label="供应商备注" align="center" prop="supplierRemark" />-->
<!--      <el-table-column label="成本单价" align="center" prop="costPrice" />-->
<!--      <el-table-column label="密度单位" align="center" prop="densityUnit" />-->
<!--      <el-table-column label="是否库存预警" align="center" prop="stockWarning">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.stockWarning" />-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="库存下限" align="center" prop="stockLowerLimit" />-->
<!--      <el-table-column label="库存上限" align="center" prop="stockUpperLimit" />-->
<!--      <el-table-column label="面纸名称" align="center" prop="facePaperName" />-->
<!--      <el-table-column label="瓦楞纸1名称" align="center" prop="flutePaper1Name" />-->
<!--      <el-table-column label="瓦楞纸2名称" align="center" prop="flutePaper2Name" />-->
<!--      <el-table-column label="瓦楞纸3名称" align="center" prop="flutePaper3Name" />-->
<!--      <el-table-column label="里纸名称" align="center" prop="innerPaperName" />-->
<!--      <el-table-column label="瓦楞纸1坑型" align="center" prop="flutePaper1FluteType" />-->
<!--      <el-table-column label="瓦楞纸2坑型" align="center" prop="flutePaper2FluteType" />-->
<!--      <el-table-column label="瓦楞纸3坑型" align="center" prop="flutePaper3FluteType" />-->
<!--      <el-table-column label="生管对应名称" align="center" prop="productionCorrespondingName" />-->
<!--      <el-table-column label="配置" align="center" prop="configuration" />-->
      <el-table-column label="是否为基础材质" align="center" prop="isBaseMaterial">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isBaseMaterial" />
        </template>
      </el-table-column>
<!--      <el-table-column label="科目" align="center" prop="subject" />-->
<!--      <el-table-column label="是否停用" align="center" prop="isDisabled">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isDisabled" />-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="生管材质对照2" align="center" prop="productionMaterialCorrespondence2" />-->
<!--      <el-table-column label="生管材质对照3" align="center" prop="productionMaterialCorrespondence3" />-->
<!--      <el-table-column label="生管材质对照4" align="center" prop="productionMaterialCorrespondence4" />-->
<!--      <el-table-column label="生管材质对照5" align="center" prop="productionMaterialCorrespondence5" />-->
<!--      <el-table-column label="生管材质对照6" align="center" prop="productionMaterialCorrespondence6" />-->
<!--      <el-table-column label="生管材质对照7" align="center" prop="productionMaterialCorrespondence7" />-->
<!--      <el-table-column label="面纸克重" align="center" prop="facePaperWeight" />-->
<!--      <el-table-column label="瓦楞纸1克重" align="center" prop="flutePaper1Weight" />-->
<!--      <el-table-column label="芯纸1克重" align="center" prop="corePaper1Weight" />-->
<!--      <el-table-column label="瓦楞纸2克重" align="center" prop="flutePaper2Weight" />-->
<!--      <el-table-column label="芯纸2克重" align="center" prop="corePaper2Weight" />-->
<!--      <el-table-column label="瓦楞纸3克重" align="center" prop="flutePaper3Weight" />-->
<!--      <el-table-column label="里纸克重" align="center" prop="innerPaperWeight" />-->
<!--      <el-table-column label="默认库存单位" align="center" prop="defaultStorageUnit" />-->
<!--      <el-table-column label="代用材质" align="center" prop="substituteMaterial" />-->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:base-material:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:base-material:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BaseMaterialForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { BaseMaterialApi, BaseMaterialVO } from '@/api/erp/basematerial'
import BaseMaterialForm from './BaseMaterialForm.vue'
import BaseMaterialParametersList from './components/BaseMaterialParametersList.vue'
import BaseMaterialRemarksList from './components/BaseMaterialRemarksList.vue'

/** ERP基础资料-材质资料 列表 */
defineOptions({ name: 'BaseMaterial' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<BaseMaterialVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  materialName: undefined,
  materialType: undefined,
  materialTypeId: undefined,
  fluteType: undefined,
  layer: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BaseMaterialApi.getBaseMaterialPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BaseMaterialApi.deleteBaseMaterial(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BaseMaterialApi.exportBaseMaterial(queryParams)
    download.excel(data, 'ERP基础资料-材质资料.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 材质类型下拉框
const materialTypeList = ref<{ id: string; typeName: string }[]>([]);

// const queryParams = ref({ materialTypeId: "" });
// **获取材质类型数据**
const getBaseMaterialType = async () => {
  try {
    const response = await BaseMaterialApi.getBaseMaterialType();
    console.log("接口返回的数据：", response) // 打印整个返回数据
    console.log("接口返回的数据：", response.data) // 打印整个返回数据
    if (response) {
      materialTypeList.value = response;
    }
  } catch (error) {
    console.error("获取材质类型失败：", error);
  }
};
const selectedMaterialType = ref(null) // 默认未选择
// **选中材质类型后，填充名称 & 传递 ID**
const handleMaterialTypeChange = (id: string) => {
  const selected = materialTypeList.value.find(item => item.id === id);
  queryParams.materialTypeId = id; // 传递给后端
  queryParams.materialType = selected ? selected.typeName : ""; // 仅用于前端显示
};

/** 初始化 **/
onMounted(() => {
  Promise.all([getList(), getBaseMaterialType()]);
})
</script>
